package com.code.monitor.handler;

import com.code.monitor.model.CacheManager;
import com.code.monitor.utils.PushMessageUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleUserEventChannelHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author ggh
 * @date 2023/4/24
 */
@ChannelHandler.Sharable
public class WebSocketConnectHandler extends SimpleUserEventChannelHandler<WebSocketServerProtocolHandler.HandshakeComplete> {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketMessageHandler.class);

    @Override
    protected void eventReceived(ChannelHandlerContext ctx, WebSocketServerProtocolHandler.HandshakeComplete evt) throws Exception {
        if (!CacheManager.existWebSubscriberKey((SocketChannel) ctx.channel())) {
            logger.info("{}:websocket端建立连接", ctx.channel().remoteAddress());
            CacheManager.addWebSubscriber((SocketChannel) ctx.channel());
            PushMessageUtil.pushMessageToSubscriber((SocketChannel) ctx.channel());
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        if (CacheManager.existWebSubscriberKey((SocketChannel) ctx.channel())) {
            CacheManager.getWebSubscriberList().remove(ctx.channel());
            logger.info("{}:websocket端断开连接", ctx.channel().remoteAddress());
            return;
        }
        super.channelInactive(ctx);
    }
}
